package com.electric.qrapp.webView

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.webkit.JavascriptInterface
import androidx.activity.viewModels
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.lifecycleScope
import com.electric.qrapp.R
import com.electric.qrapp.databinding.ActivityWebViewBinding
import com.electric.qrapp.ui.base.act.BaseActivity
import com.electric.qrapp.ui.file.newfile.NewFileActivity
import com.electric.qrapp.utils.data.DataStoreUtils
import com.electric.qrapp.utils.function.*
import com.electric.qrapp.utils.system.Constants
import com.electric.qrapp.utils.system.showLog
import com.electric.qrapp.utils.system.showToast
import com.electric.qrapp.utils.view.LoadingUtils
import com.huawei.hms.hmsscankit.ScanUtil
import com.huawei.hms.ml.scan.HmsScan
import com.tencent.smtt.sdk.WebView
import dagger.hilt.android.AndroidEntryPoint


@AndroidEntryPoint
class WebViewActivity : BaseActivity<ActivityWebViewBinding>() {


    //    private val url = "http://10.1.41.186:8080/"
//    private val url = "file:///android_asset/h5/test.html"
    private val url = "http://101.43.251.36/appWeb/"


    private val vm: WebViewViewModel by viewModels()


    override fun onCreate(savedInstanceState: Bundle?) {
        setTheme(R.style.Theme_QRApp)
        super.onCreate(savedInstanceState)

    }


    override fun setBindingData() {

    }

    override fun getLayoutId(): Int = R.layout.activity_web_view

    override fun initView() {
        initListener()

    }


    /**
     *LiveData监听
     *
     */
    private fun initListener() {
        vm.vmLoc.observe(this) {
            showLog("定位结果~=> $it")
            dataBinding.wv.evaluateJavascript("javascript:getLocationResult(\"${it}\")") {

            }
        }

        vm.vmAlbum.observe(this) {
            dataBinding.wv.evaluateJavascript("javascript:getAlbumResult(\"$it\")") {}
        }

        vm.loadingLiveDate.observe(this) {
            showLoad(it)
        }

        vm.albumPermissionListener.observe(this) {
            dataBinding.wv.evaluateJavascript("javascript:getAlbumPermissionResult(\"$it\")") {

            }
        }

        vm.filePermissionListener.observe(this) {
            dataBinding.wv.evaluateJavascript("javascript:getFilePermissionResult(\"'$it\")") {

            }
        }


        lifecycle.addObserver(object : LifecycleEventObserver {
            override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
                when (event) {
                    Lifecycle.Event.ON_DESTROY -> {
                        dataBinding.wv.run {
                            clearCache(true)
                            clearHistory()
                        }
                    }
                    else -> {}
                }
            }
        })
    }


    override fun initData() {
        dataBinding.wv.init(this@WebViewActivity, null, LoadingUtils())
        dataBinding.wv.loadUrl(this@WebViewActivity.url)
        with(dataBinding.wv) {
            addJavascriptInterface(
                JavaScriptMethods(this@WebViewActivity, dataBinding.wv),
                "android"
            )
        }

        lifecycleScope
            .launchWhenCreated {
                try {
                    DataStoreUtils.init(this@WebViewActivity)
                } catch (e: Exception) {
                    showLog("初始化DataStore失败，because: $e")
                }
            }
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            Constants.REQ_SCAN -> {
                if(resultCode== RESULT_OK) {
                    val obj = data?.getParcelableExtra<HmsScan>(ScanUtil.RESULT)?.originalValue
                    dataBinding.wv.loadUrl("javascript:getScanResult('${GsonUtils.gsonString(obj)}')")
                }else{
                    showToast(this,"您必须同意此权限才能使用选取图片")
                }
            }
            Constants.REQ_LOCATION -> {
                if(resultCode== RESULT_OK) {
                    vm.getLocation(this)
                }else{
                    showToast(this,"定位失败,您必须同意此权限才是定位!")
                }
            }

            else -> {
            }
        }
    }


    override fun onBackPressed() {
        if (dataBinding.wv.canGoBack()) {
            dataBinding.wv.goBack()
            return;
        }
        if (vm.finishAct()) {
            finish()
        }
        return
//        super.onBackPressed()

    }


    inner class JavaScriptMethods(private var mContext: Context?, webView: WebView?) {

        private var mWebView: WebView? = webView

        @JavascriptInterface
        fun scan() {
            mWebView?.post {
                ScanUtils.startScan(mContext as FragmentActivity, Constants.REQ_SCAN)
            }
        }

        @JavascriptInterface
        fun toAlbum(num: String?) {
            mWebView?.post {
                PhotoUtils.getDefPhoto(
                    context = mContext,
                    photoCount = if (num.isNullOrBlank()) 1 else num.toInt()
                ) { list ->
                    vm.compressFile(mContext!!, list)
                }
            }
        }


        @JavascriptInterface
        fun toLocation() {
            mWebView?.post {
                vm.getLocation(mContext!!)
            }
        }


        @JavascriptInterface
        fun toPreview(url: String) {
            mWebView?.post {
                startActivity(
                    Intent(this@WebViewActivity, NewFileActivity::class.java)
                        .putExtra(NewFileActivity.FILE_URL, url)
                )
            }
        }


        @JavascriptInterface
        fun toAlbumPermission() {
            mWebView?.post {
                albumPermission(this@WebViewActivity, vm.albumPermissionListener)
            }
        }

        @JavascriptInterface
        fun toFilePermission() {
            mWebView?.post {
                filePermission(this@WebViewActivity, vm.filePermissionListener)
            }
        }

        @JavascriptInterface
        fun toClearCache() {
            mWebView?.post {
                mWebView?.clearCache(true)
                mWebView?.clearHistory()
            }
        }
    }
}